var express = require('express');
var router = express.Router();
const db=require('../db/db');
var sd = require('silly-datetime');
let ArtStore=require('../public/contract/ArtStore.json')
let Web3 = require('web3')
let web3 = new Web3(Web3.givenProvider || 'ws://172.17.147.23:8545');
let MyContract = new web3.eth.Contract(ArtStore, "0x7b23dd3a56a6bff4accc0f1d5bb53c381dc97752")
router.get("/",function (){
    console.log("访问到后端")
    // saveProduct(product)
})
let sellForm=["定价出售","拍卖"]
let workStatus=["selling","sold","failed"]
new newProductEventListener();
function newProductEventListener(){
    updateWorks()
    updateWorksInTran()
    updateSecondSell()
    addParticipateAuction()
    delParticipateAuction()
}
// 二次买卖
function secondaryTrade(product){
    let {tokenId,SellForm,price,auctionId,put_time}=product //给id和出售方式,nft_id
    let status="selling"
    let sql=`update shop set status=?,form_of_sale=?,put_time=?,price=?,auction_id=? where nft_id=?`;
    if(auctionId==0){
        auctionId=null;
    }
    let time=sd.format(put_time, 'YYYY-MM-DD HH:mm:ss')
    db.query(sql,[status,sellForm[SellForm],time,price,auctionId,tokenId],function (err,result) {
        if(err) {
            console.log(err);
            return;
        }else {
            console.log("开启二次售卖!!")
        }
    })
}

// 铸造ntf成功后改变商品状态为出售selling 并识别拍卖或者出售
function agree(product){
    let {worksId,tokenId,sell_form,price,put_time,auctionId}=product //给id和出售方式,nft_id
    let status="selling"
    let sql=`update shop set status=?,nft_id=?,form_of_sale=?,price=?,put_time=?,auction_id=? where id=?` ;
    let time=sd.format(put_time, 'YYYY-MM-DD HH:mm:ss')
    console.log(sell_form)
    db.query(sql,[status,tokenId,sellForm[sell_form],price,time,auctionId,worksId],function (err,result) {
        if(err){
            console.log(err);
            return;
        }else{
            console.log("商品上链成功!!")
        }
    })
}


//交易后改变状态
function tradesuccess(product){
    let {tokenId,owner,status}=product //给id
    // if(owner=="0x0000000000000000000000000000000000000000"){
    //     owner=null;
    // }
    let sql=`update shop set status=?,owner=? where nft_id=?` ;
    db.query(sql,[workStatus[status],owner,tokenId],function (err,result) {
        if(err){
            console.log(err);
            return
        }else{
            console.log("交易成功")
        }
    })
}

//上链监听事件
function updateWorks(){
    MyContract.events.updateWorks({
        fromBlock: 'latest'
    }, (err, res) => {
        if (err) {
            console.log(err)
        }
        console.log(res)
        agree(res.returnValues)
    })
// })
}
//交易转权监听事件
function updateWorksInTran(){
    MyContract.events.updateWorksInTran({
        fromBlock: 'latest'
    }, (err, res) => {
        if (err) {
            console.log(err)
        }
        tradesuccess(res.returnValues)
    })
}
//进行二次售卖监听事件
function updateSecondSell(){
    MyContract.events.updateSecondSell({
        fromBlock: 'latest'
    }, (err, res) => {
        if (err) {
            console.log(err)
        }
        secondaryTrade(res.returnValues)
        console.log(res.returnValues)
    })
}

//添加用户参加拍卖记录
function insertParticipateAuction(product){
    let {userAddres,tokenId}=product //获取用户地址和tokenId
    console.log(userAddres,tokenId)
    let sql=`select * from participate_auction where user_addres=? and token_id=?`;
    console.log(sql)
    db.query(sql,[userAddres,tokenId],function (err,result) {
        if(err){
            console.log(err)
            return;
        }
        console.log(result)
        if(result.length==0){
            let sql1=`insert into participate_auction(user_addres,token_id) values(?,?)` ;
            db.query(sql1,[userAddres,tokenId],function (err1,result1) {
                if(err1){
                    console.log(err1);
                    return
                }else{
                    console.log("添加用户参加拍卖记录成功")
                }
            })
        }else {
                console.log("已有用户参加拍卖记录")
        }
    })
}

//删除用户参加拍卖记录
function deleteParticipateAuction(product){
    let {tokenId}=product //获取用户地址和tokenId
    let sql=`DELETE FROM participate_auction WHERE token_id = ?` ;
    console.log("token:"+tokenId)
    console.log("product:"+product)
    db.query(sql,[tokenId],function (err,result) {
        if(err){
            console.log(err);
            return
        }else{
            console.log(result)
            console.log("删除用户参加拍卖记录成功")
        }
    })
}

//用户参加哪场拍卖记录监听事件
function addParticipateAuction(){
    MyContract.events.addParticipateAuction({
        fromBlock: 'latest'
    }, (err, res) => {
        if (err) {
            console.log(err)
        }
        console.log(res.returnValues)
        // console.log("插入记录"+res.returnValues)
        insertParticipateAuction(res.returnValues)
    })
}
//拍卖结束删除用户参加哪场拍卖记录监听事件
function delParticipateAuction(){
    MyContract.events.delParticipateAuction({
        fromBlock: 'latest'
    }, (err, res) => {
        if (err) {
            console.log(err)
        }
        deleteParticipateAuction(res.returnValues)
        console.log(res.returnValues)
    })
}


module.exports = router;

